package cn.duhengkui.national.valuelist.context;

import java.util.ArrayList;
import java.util.Set;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.InitializingBean;

import cn.duhengkui.national.valuelist.core.data.util.Entitys;
import cn.duhengkui.national.valuelist.core.entity.BaseEntity;
import cn.duhengkui.national.valuelist.tool.ClassPathScanHandler;


/**   
 * <table border="1">
 *	<tr><td>包名称：</td><td>cn.duhengkui.national.valuelist.context</td></tr>
 *	<tr><td>类名称：</td><td>EntityLoader</td></tr>
 *	<tr><td>类描述：</td><td>实体对象加载监听器，用于系统启动是监听entityPackages配置下的所有实体对象</td></tr>
 *	<tr><td>创建人：</td><td>杜恒奎</td></tr>
 *  <tr><td>创建时间：</td><td>2018年6月7日/下午3:00:05</td></tr> 
 *  <tr><td>版本：</td><td>1.0.0</td></tr>
 * </table>   
 *     
 */
public class EntityLoader implements InitializingBean{
	
	//private static final String CLASS_PATH_EXPRESSION_VARIABLE = "entityPackages";

	protected static final Logger logger = LoggerFactory.getLogger(EntityLoader.class);


	private String packages = "";


	public void setPackages(String packages) {
		this.packages = packages;
	}


	@Override
	public void afterPropertiesSet() throws Exception {
		long time = System.currentTimeMillis();
		logger.info("Begin scan entity ");
		//String[] entityPackages = packages.split(",");
		ClassPathScanHandler scanHandler = new ClassPathScanHandler(true, true, new ArrayList<String>());
		//for(String entityPackage : entityPackages) {
			Set<Class<?>> classSet = scanHandler.getPackageAllClasses(packages, true,false);
			logger.debug("scan all package : ");
			for(Class<?> clazz : classSet) {
				if(clazz.getSuperclass() != null && clazz.getSuperclass().equals(BaseEntity.class)) {
					@SuppressWarnings("unchecked") Class<? extends BaseEntity> entityClass = (Class<? extends BaseEntity>)clazz;
					if(EntityContext.exists(entityClass))
						continue;
					logger.debug("found entity class : " + entityClass.getName());
					Entitys entitys = Entitys.newInstance(entityClass);
					EntityContext.addEntity(entityClass, entitys);
				}
			}
		//}
		logger.info("EntityLoader : initialization started in " + (System.currentTimeMillis() - time) + " ms");
		
	}

}
